<template>
  <div>
    <div v-loading="loading">
      <!--动态组件 ，根据is的值来确定渲染哪个组件 -->
      <component :is="dynaPath" ref="actFormPath" />
    </div>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <el-button @click="cancel">{{ $t('取消') }}</el-button>
      <el-button type="info" @click="showXml">{{ $t('查看流程') }}</el-button>
      <el-button type="primary" @click="submitForm('process')">{{ $t("保存并启动流程") }}</el-button>
    </div>
    <el-dialog v-if="imageOpen" :title="$t('流程图')" :close-on-click-modal="false" :visible.sync="imageOpen" width="50%" custom-class="dialogForm" append-to-body :lock-scroll="false">
      <div>
        <actFlowFormChart v-if="processData.processDefinitionKey !== 'act_free_flow_approval'" ref="actFlowFormChart" />
      </div>

      <span v-if="currentChildNode.processKey === 'act_free_flow_approval'">
        <div style="text-align: center;margin-top: 50px;margin-bottom: 50px">
          <span v-html="$t('该功能配置流程为自由流审批<br>')" />
          <span v-html="$t('在流程启动时由流程发起人选择审批人<br>')" />
          <span v-html="$t('选择的审批人按顺序进行审批<br>')" />
        </div>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { bindingDataId, getHistoryApproval, getNodeFormUrl, getWfBusNode, restart } from '@/api/act/busFlow/wfBusNode'
import { appsVariable } from '@/qiankun/registerApp'
import { importComponent } from '@/qiankun'
import { getAsyncComponent } from '@/utils'
import { startProcessByNode } from '@/api/act/process/actProcess'
import ActFlowFormChart from '@/views/act/process/actFlowFormChart.vue'

export default {
  name: 'ActTaskForm',
  components: {
    ActFlowFormChart
  },
  props: {
    busName: {
      type: String,
      default: undefined
    }
  },
  data() {
    return {
      otherBtnHide: false,
      loading: false,
      actFormPath: undefined,
      formDisabled: false,
      // 流程图片是否展示
      imageOpen: false,
      processData: {},
      // 是否需要再次启动新的流程（业务阶段的流程）
      reStartFlag: false,
      // 当前二级节点
      currentChildNode: {
        viewNode: true
      },
      dynaPath: ''
    }
  },
  created() {
  },
  mounted: function() {
  },
  methods: {
    // 关闭form页面
    // 取消按钮
    cancel() {
      this.$parent.$parent.processOpen = false
      this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.processOpen !== undefined) {
        this.$parent.$parent.processOpen = false
      }
    },
    // 打开流程详情页面显示XML
    showXml() {
      this.imageOpen = true
      this.$nextTick(() => {
        this.$refs.actFlowFormChart.init(this.currentChildNode.processKey)
      })
    },
    // 二级节点点击事件
    childrenNodeClick(id) {
      this.reStartFlag = false
      // 如果ID为空则是没有配置流程二级节点
      if (id !== null && id !== undefined && id !== '') {
        // 根据ID查询wfBusNode表记录
        getWfBusNode(id).then(response => {
          this.currentChildNode = response.data
          if (this.currentChildNode.dataId && this.currentChildNode.actStatus && this.currentChildNode.actStatus !== 'N') {
            this.reStartFlag = true
          }
          // 查询该节点是否有历史的审批记录
          this.getHistoryApproval(this.currentChildNode.id)
          getNodeFormUrl(this.currentChildNode).then(response => {
            // 当前节点的表单地址
            this.currentChildNode.actFormPath = response.data
            this.importFormPath(response.data)
            // 刷新流转记录
            // this.refreshRecord()
            // if (this.$refs.miniProcess?.getParentNodeRightData !== undefined) {
            //   this.$refs.miniProcess.getParentNodeRightData()
            // }
          })
        })
      } else {
        // this.loading.form = false
        this.$message.error('流程配置错误,请配置流程二级节点')
      }
    },
    // 查询该节点的历史审批记录
    getHistoryApproval(id) {
      getHistoryApproval(id).then((response) => {
        if (response.code === 200) {
          this.historyApproval = response.data
          // 当前二级节点的ID
          this.currentChildId = id
        } else {
          this.msgError(response.msg)
        }
      })
    },
    // 引入表单组件
    async importFormPath(menuPath) {
      console.log('-------menuPath111111111111---------', menuPath)
      // 循环所有子应用，如果是子应用的菜单，则引用他们的组件
      const apps = appsVariable()
      const newPath = menuPath.lastIndexOf('\/')
      var strPath = ''
      var subAppName
      var isSubAppMenuPath = false
      var subApp
      if (apps) {
        apps.forEach(element => {
          if (menuPath && menuPath.includes(element.name)) {
            isSubAppMenuPath = true
            subAppName = element.name
            subApp = element
            return
          }
        })
      }
      if (isSubAppMenuPath) {
        strPath = menuPath.substring(newPath + 1, menuPath.length)
        const componentName = strPath + '_' + subAppName
        // 导入子应用的组件
        await importComponent(subApp, componentName)
        this.actFormPath = componentName
        this.dynaPath = componentName
        console.log(this.menuPath)
      } else {
        this.dynaPath = getAsyncComponent(menuPath)
      }
      this.$bus.$once('async_done', () => {
        this.$nextTick(async function() {
          const data = {}
          if (this.reStartFlag) {
            data.id = undefined
          } else {
            data.id = this.currentChildNode.dataId
          }
          data.formId = this.currentChildNode.formId
          // 如果id没有值就统一设置为undefined,方便子页面判断
          if (data.id === null || data.id === '') {
            data.id = undefined
          }
          // 默认流程标题
          var actTitle = this.busName + '-' + this.$t(this.currentChildNode.wfConfigNode.nodeName)

          // file对象中增加业务ID
          data.fileList = this.currentChildNode.fileList
          data.wfNodeId = this.currentChildNode.id
          data.actTitle = actTitle
          data.processKey = this.currentChildNode.processKey
          data.roundId = this.roundId
          data.nodeName = this.currentChildNode.wfConfigNode.nodeName
          data.meeting = this.currentChildNode.meeting
          data.meetingType = this.currentChildNode.meetingType
          console.log('this.$refs.actFormPath.init', data)

          this.$refs.actFormPath && await this.$refs.actFormPath.init(data)
          // 控制保存按钮等按钮是否隐藏
          this.$refs.actFormPath._data.btnHide = true
          // this.$refs.actFormPath._data.otherBtnHide = true
          // 允许上传附件
          this.$refs.actFormPath._data.otherBtnHide = false
          // 控制其他按钮是否隐藏
          // this.formDisabled = false
          if (this.currentChildNode.actId !== null && this.currentChildNode.actId !== '' && this.currentChildNode.actStatus !== 'Z') {
            this.$refs.actFormPath._data.otherBtnHide = true
            // this.formDisabled = true
          }
        })
      })
      // this.loading.form = false
    },
    /**
     * 保存表单和保存并启动流程
     * @param type  保存表单：save  保存并启动流程:process
     */
    submitForm(type) {
      console.log('-----submitForm-----', type)
      // 保存表单时清除校验
      if (this.currentChildNode.processKey) {
        this.clearCheck(type)
      }

      // 设置必传附件校验
      this.checkFileRequired(type)
      // 业务阶段当前存在流程，这里的入口只能重新启动一下流程
      if (this.reStartFlag) {
        var actFormPath = this.currentChildNode.actFormPath
        restart(this.currentChildNode).then((res) => {
          console.log('----restart方法----', res)
          this.currentChildNode = res.data
          this.currentChildNode.actFormPath = actFormPath
          // 掉用子组件保存数据
          this.$refs.actFormPath.submitForm('actSave').then((dataId) => {
            console.log('----submitForm---actSave', dataId)
            // 恢复校验
            if (this.currentChildNode.processKey) {
              this.addCheck(type)
            }
            if (dataId === undefined) {
              dataId = this.currentChildNode.dataId
            }
            // 将dataId保存到wfBusNode表
            bindingDataId(this.currentChildNode.id, dataId).then((response) => {
              if (response.code === 200) {
                // 保存结束后, 重新加载该表单. 目的是为了让子表及附件获取已经录入的ID. 防止再次保存造成新增重复
                // this.childrenNodeClick(this.currentChildNode.id)
                console.log('---restart---bindingDataId---', response)
                // 点击的按钮是保存并启动流程
                if (type === 'process') {
                  console.log('---restart---bindingDataId---type---', type)
                  if (this.currentChildNode.processKey !== '' && this.currentChildNode.processKey !== null) {
                    console.log('---restart---bindingDataId---startProcess---', response.data)
                    // 启动流程
                    this.startProcess(response.data)
                  } else {
                    this.$message.error(this.$t('流程启动失败,该节点未配置流程'))
                  }
                }
              } else {
                this.msgError(response.msg)
              }
            })
          }).catch(e => {
            // 恢复校验
            this.addCheck(type)
            console.error('error', e)
            this.msgError(this.$t('保存失败,数据未绑定成功'))
          })
        })
      } else {
        // 掉用子组件保存数据
        this.$refs.actFormPath.submitForm('actSave').then((dataId) => {
          // 恢复校验
          if (this.currentChildNode.processKey) {
            this.addCheck(type)
          }
          if (dataId === undefined) {
            dataId = this.currentChildNode.dataId
          }
          // 将dataId保存到wfBusNode表
          bindingDataId(this.currentChildNode.id, dataId).then((response) => {
            if (response.code === 200) {
              // 保存结束后, 重新加载该表单. 目的是为了让子表及附件获取已经录入的ID. 防止再次保存造成新增重复
              // this.childrenNodeClick(this.currentChildNode.id)
              // 点击的按钮是保存并启动流程
              if (type === 'process') {
                if (this.currentChildNode.processKey !== '' && this.currentChildNode.processKey !== null) {
                  // 启动流程
                  this.startProcess(response.data)
                } else {
                  this.$message.error(this.$t('流程启动失败,该节点未配置流程'))
                }
              }
            } else {
              this.msgError(response.msg)
            }
          })
        }).catch(e => {
          // 恢复校验
          this.addCheck(type)
          console.error('error', e)
          this.msgError(this.$t('保存失败,数据未绑定成功'))
        })
      }
    },
    // 再次启动
    restart() {
      this.$confirm(this.$t('是否确认再次发起') + '?', this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      })
        .then(() => {
          restart(this.currentChildNode).then((response) => {
            this.childrenNodeClick(response.data.id)
          })
        })
        .catch(function() {})
    },
    // 启动流程
    startProcess: function() {
      // 启动流程时候传入的参数
      const processData = {}
      // 待办标题
      if (this.$refs.actFormPath._data.form !== undefined && this.$refs.actFormPath._data.form.actTitle !== undefined) {
        processData.title = '「' + this.busName + '」' + this.currentChildNode.wfConfigNode.nodeName + ':' + this.$refs.actFormPath._data.form.actTitle
      } else {
        processData.title = '「' + this.busName + '」' + this.currentChildNode.wfConfigNode.nodeName
      }
      // 业务表名
      processData.dataTable = 'wf_bus_node'
      // 业务ID
      processData.dataId = this.currentChildNode.id
      // 业务表单地址
      processData.formPath = this.currentChildNode.actFormPath
      // 使用的流程表单ID
      processData.formId = this.currentChildNode.formId
      // 打印地址
      var actViewPath = processData.formPath.replace(/(.*)Form/, '$1View')
      processData.viewPath = actViewPath

      // 菜单标识(根据菜单标识判断的走哪个流程)
      processData.processKey = this.currentChildNode.processKey
      startProcessByNode(processData, () => {
        // 从新点击二级节点
        // this.childrenNodeClick(this.currentChildNode.id)
        // 关闭窗口
        this.closeForm()
      })
    },
    // 保存表单时清楚校验
    clearCheck(type) {
      console.log(type, '流程类型')
      if (type === 'save') {
        if (this.$refs.actFormPath.rules) {
          window.localStorage.setItem('fileConfigRequired', false)
          var keys = Object.keys(this.$refs.actFormPath.rules)
          // 普通表单处理
          if (this.$refs.actFormPath.$refs.form?.clearValidate) {
            this.$refs.actFormPath.$refs.form.clearValidate()
          }
          // 多sheet页表单处理
          if (this.$refs.actFormPath?.clearValidate) {
            this.$refs.actFormPath.clearValidate()
          }

          if (keys.length > 0) {
            this.formRulesTemp = {}
            for (let i = 0; i < keys.length; i++) {
              this.formRulesTemp[keys[i]] = this.$refs.actFormPath.rules[keys[i]]
              this.$refs.actFormPath.rules[keys[i]] = []
            }
          }
        }
      }
    },
    // 提交流程时校验
    addCheck(type) {
      if (type === 'save') {
        window.localStorage.setItem('fileConfigRequired', true)
        var keys = Object.keys(this.formRulesTemp)
        if (keys.length > 0) {
          for (let i = 0; i < keys.length; i++) {
            this.$refs.actFormPath.rules[keys[i]] = this.formRulesTemp[keys[i]]
          }
        }
      }
    },
    /**
     * 保存前必传附件校验设置
     * actFormPath表单init方法执行后会覆盖fileList, 目前拿不到接口返回的最新的
     * 数据, 所以放在提交前校验
     */
    checkFileRequired(type) {
      const wConfigNode = this.currentChildNode.wfConfigNode
      if (wConfigNode && wConfigNode.checkFile) {
        // this.$refs.actFormPath.pojo['filelist'] 拿到自定义表单的附件
        var fileList = (this.$refs.actFormPath.form && this.$refs.actFormPath.form.fileList) ? this.$refs.actFormPath.form.fileList
          : ((this.$refs.actFormPath.pojo && this.$refs.actFormPath.pojo['filelist']) ? this.$refs.actFormPath.pojo['filelist'] : [])
        if (wConfigNode.checkFile.length === 0) {
          // 配置中, 必填附件为空, 表单里的附件理论上都应该为非必填
          fileList.forEach(item => {
            item.checkRequired = 'false'
          })
        } else {
          // 配置中, 必填附件不为空, 看一下那个目录需要必填设置上必填标识
          var isProcessBtn = (this.currentChildNode.actStatus === 'N' || this.currentChildNode.actStatus === 'Z' || !this.currentChildNode.actStatus) && this.currentChildNode.processKey && this.currentChildNode.startProcess && this.currentChildNode.editNode
          fileList.forEach(item => {
            // true表示需要必填, 但是只有在启动流程时才生效, 保存时不需要必填
            if (type === 'save') {
              // 保存按钮不校验附件必填
              item.checkRequired = 'false'
            } else if (wConfigNode.checkFile.includes(item.directoryId) && type === 'process') {
              item.checkRequired = 'true'
            } else if (wConfigNode.checkFile.includes(item.directoryId) && !isProcessBtn) {
              // 如果页面上没有流程按钮, 也需要校验附件必填情况
              item.checkRequired = 'true'
            } else {
              item.checkRequired = 'false'
            }
          })
        }
      } else {
        var fileLists = (this.$refs.actFormPath.form && this.$refs.actFormPath.form.fileList) ? this.$refs.actFormPath.form.fileList
          : ((this.$refs.actFormPath.pojo && this.$refs.actFormPath.pojo['filelist']) ? this.$refs.actFormPath.pojo['filelist'] : [])
        if (type === 'save' && !this.isEmpty(fileLists)) {
          fileLists.forEach(item => {
            item.checkRequired = 'false'
          })
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">

.row{
  display: flex;
  column-gap: 20px;
  .col-right{
    width: 34%;
    min-width: 34%;
    max-width: 34%;
  }
  .col-left{
    flex: 1;
    width: calc(100% - 34% - 20px);
  }
}
.actTaskLeft{
  height: calc(100% - 35px);
  border: 1px solid #DCDFE6;
  border-top: 0;
}
.actTaskForm{
  .printForm {
    width:calc(100% - 30px);
  }
  /deep/.area-header{
    margin: 10px 0;
  }
  /deep/.approvalRecord {
    width:calc(100% - 30px);
    margin-bottom: 10px;
  }
}
.tabTask{
    border-left: 1px solid #DCDFE6;
    display: flex;
    span{
      display: inline-flex;
      align-items: center;
      justify-content: center;
      height: 35px;
      // line-height: 30px;
      background: #fff;
      border: 1px solid #DCDFE6;
      color: #606266;
      padding: 0 15px;
      cursor: pointer;
      text-align: center;
      border-left: 0;
      font-weight: bold;
    }
    .active{
      border-top: 1px solid #46a6ff;
      border-bottom: 0;
    }
    .last{
      flex: 1;
      border: 0;
      border-bottom: 1px solid #DCDFE6;
    }
}
.maxWid-400{
  max-width: 400px;
}
.accraditation{
  position: relative;
  height: calc(100% - 25px);
  .el-form{
    height: calc(100% - 50px);
    overflow: auto;
    margin-right: -18px;
  }
  .actFooter{
    position: absolute;
    right: 0;
    bottom: -30px;
  }
}
.edit-icon{
  cursor: pointer;
  color:#46a6ff;
  margin-left: 10px;
}
/deep/.el-loading-mask {
  z-index: 2200;
}
.tip-block{
  padding: 15px;
  background-color: #fafafa;
  border: 1px solid #eaeefb;
  margin-bottom: 10px;
  border-radius: 4px;
  font-weight: bold;
  font-size: 14px;
  display: flex;
  align-items: center;
  column-gap: 5px;
  margin-right: 30px;
  color: #FF9000;
  i{
    color: #FF9000;
    font-weight: bold;
    font-size: 16px;
  }
}
.area-header-act{
  white-space: nowrap;
  overflow: hidden;
  max-width: 95%;
  display: inline-block;
  text-overflow: ellipsis;
}

@media (max-width: 1200px) {
  .actFooter {
    zoom: 0.7
  }
}
</style>
